<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/24 13:59:44 $)
// $RCSfile: functions_users.php,v $ : $Revision: 1.28 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

define("MAIL_VERIFICATION", 1);
define("MAIL_SUCCESSREG", 2);

/**
* Updates the SLA Plan for the given user
*/
function updateUserSLAPlan($userid, $slaplanid)
{
	global $dbCore;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."users` SET `slaplanid` = '". intval($slaplanid) ."' WHERE `userid` = '". intval($userid) ."';");

	return true;
}

/**
* Updates the SLA Plan for the given user group
*/
function updateUserGroupSLAPlan($usergroupid, $slaplanid)
{
	global $dbCore;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."usergroups` SET `slaplanid` = '". intval($slaplanid) ."' WHERE `usergroupid` = '". intval($usergroupid) ."';");

	return true;
}

/**
* Delete users based on user emails
*/
function deleteUsersBasedOnUserEmails($useremailidlist)
{
	global $dbCore;

	if (!_is_array($useremailidlist))
	{
		return false;
	}

	// Get the user ids
	$useridlist = array();
	$dbCore->query("SELECT `userid` FROM `". TABLE_PREFIX ."useremails` WHERE `useremailid` IN (". buildIN($useremailidlist) .");");
	while ($dbCore->nextRecord())
	{
		if (!in_array($dbCore->Record["userid"], $useridlist))
		{
			$useridlist[] = $dbCore->Record["userid"];
		}
	}

	deleteUsers($useridlist);
}

/**
* Delete the given users
*/
function deleteUsers($useridlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($useridlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."users` WHERE `userid` IN (". buildIN($useridlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."useremails` WHERE `userid` IN (". buildIN($useridlist) .");");

	deleteCustomFieldValue(CUSTOMFIELD_USER, $useridlist);

	return true;
}

/**
* Delete the given user groups
*/
function deleteUserGroups($usergroupidlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($usergroupidlist))
	{
		return 0;
	}

	$finalusergroupidlist = array();
	// Fetch all given user groups and make sure they are not master user groups
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."usergroups` WHERE `usergroupid` IN (". buildIN($usergroupidlist) .");");
	while ($dbCore->nextRecord())
	{
		if ($dbCore->Record["ismaster"] == 1)
		{
			return -1;
		}
		$finalusergroupidlist[] = $dbCore->Record["usergroupid"];
	}

	if (!count($finalusergroupidlist))
	{
		return 0;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."usergroups` WHERE `usergroupid` IN (". buildIN($finalusergroupidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."usergroupsettings` WHERE `usergroupid` IN (". buildIN($finalusergroupidlist) .");");

	// Build the user list to delete
	$useridlist = array();
	$dbCore->query("SELECT `userid` FROM `". TABLE_PREFIX ."users` WHERE `usergroupid` IN (". buildIN($finalusergroupidlist) .");");
	while ($dbCore->nextRecord())
	{
		$useridlist[] = $dbCore->Record["userid"];
	}
	deleteUsers($useridlist);

	// Now nuke the custom fields
	deleteCustomFieldValue(CUSTOMFIELD_USERGROUP, $finalusergroupidlist);

	rebuildUserGroupSettingsCache();

	return 1;
}

/**
* Delete a given user emails
*/
function deleteUserEmails($userid, $useremailidlist)
{
	global $dbCore;

	if (!_is_array($useremailidlist))
	{
		return false;
	}

	// First get the total number of user emails this user has
	$_totalitems = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."useremails` WHERE `userid` = '". intval($userid) ."';");

	if ($_totalitems["totalitems"] <= 1)
	{
		// We need to have ATLEAST one email assigned to a user, return error
		return -1;
	} else if (count($useremailidlist) >= $_totalitems["totalitems"]) {
		return -1;
	}	

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."useremails` WHERE `useremailid` IN (". buildIN($useremailidlist) .");");

	// Update the user email count for the given user
	updateUserEmailCount($userid);

	return 1;
}

/**
* Update the given user email
*/
function updateUserEmail($userid, $useremailid, $email)
{
	global $dbCore, $module;
	$emailchk = getUserEmail($email);
	if(!$emailchk)
	{
		$dbCore->query("UPDATE `". TABLE_PREFIX ."useremails` SET `email` = '". $dbCore->escape($email) ."' WHERE `useremailid` = '". intval($useremailid) ."';", 3, true);
	} else
	{
		return false;
	}

	if ($userid)
	{
		updateUserEmailCount($userid);
	}

	return true;
}

/**
* Assign a new email address to a user
*/
function insertUserEmail($userid, $email)
{
	global $dbCore;

	$result = $dbCore->query("INSERT INTO `". TABLE_PREFIX ."useremails` (`userid`, `email`) VALUES ('". intval($userid) ."', '". $dbCore->escape($email) ."');", 3, true);
	if (!$result)
	{
		return false;
	}

	updateUserEmailCount($userid);

	return true;
}

/**
* Updates the useremailcount in the users table
*/
function updateUserEmailCount($userid)
{
	global $dbCore;

	$_totaluseremails = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."useremails` WHERE `userid` = '". intval($userid) ."';");
	$dbCore->query("UPDATE `". TABLE_PREFIX ."users` SET `useremailcount` = '". intval($_totaluseremails["totalitems"]) ."' WHERE `userid` = '". intval($userid) ."';");
 }

/**
* Update Existing User
*/
function updateUserStaffCP($userid, $password, $usergroupid, $fullname, $ismanager)
{
	global $dbCore, $_SWIFT;

	if (!empty($password))
	{
		$passwordsql = ", `userpassword` = '". md5($password) ."', `userpasswordtxt` = '". $dbCore->escape($password) ."'";
	} else {
		unset($passwordsql);
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."users` SET `usergroupid` = '". intval($usergroupid) ."', `fullname` = '". $dbCore->escape($fullname) ."', `ismanager` = '". iif($ismanager==true, "1", "0") ."'". $passwordsql ." WHERE `userid` = '". intval($userid) ."';");

	return true;
}

/**
* Update Existing User
*/
function updateUserClientCP($userid, $fullname)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."users` SET `fullname` = '". $dbCore->escape($fullname) ."' WHERE `userid` = '". intval($userid) ."';");

	return true;
}

/**
* Get the Login Share User
*/
function getLoginShareUser($loginapi_moduleid, $loginapi_userid)
{
	global $dbCore;

	$_loginapiuser = $dbCore->queryFetch("SELECT `userid` FROM `". TABLE_PREFIX ."users` WHERE `loginapi_moduleid` = '". intval($loginapi_moduleid) ."' AND `loginapi_userid` = '". $dbCore->escape($loginapi_userid) ."';");
	if (!empty($_loginapiuser["userid"]))
	{
		return $_loginapiuser["userid"];
	}

	return false;
}

/**
* Change the validation status for user
*/
function changeUserValidationStatus($useridlist, $enabled)
{
	global $dbCore;

	if (!_is_array($useridlist))
	{
		return false;
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."users` SET `enabled` = '". intval($enabled) ."' WHERE `userid` IN (". buildIN($useridlist) .");");
	//Mahesh Slaria: email after validation....
	if ($enabled == 1)
	{
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."users` AS users LEFT JOIN `". TABLE_PREFIX ."useremails` AS useremails ON (users.userid = useremails.userid) WHERE users.userid IN (". buildIN($useridlist) .");");
		while ($dbCore->nextRecord())
		{
			$_user = $dbCore->Record;
			sendRegistrationUpdateMail(MAIL_SUCCESSREG, $_user["userid"], $_user["fullname"], $_user["email"], $_user["userpasswordtxt"]);
		}
	}
	//-------------------------------------------

	return true;
}

/**
* Insert a new user, returns false if a user with same email already exists
*/
function insertUser($enabled, $email, $password, $usergroupid, $loginapi_moduleid, $loginapi_userid, $fullname = "", $languageid = 0, $timezoneoffset = 0, $enabledst = false, $allowemail = 1, $disableoutgoingemail = false, $ismd5 = false, $ismanager = false)
{
	global $dbCore, $_SWIFT, $template;

	$template->loadLanguageSection("misc", TEMPLATE_DB);
	// Does a user exist with this email address?
	$emailuserid = getUserEmail($email);
	if (!$emailuserid)
	{
		$txtpassword = $password;

		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."users` (`usergroupid`, `fullname`, `userpassword`, `userpasswordtxt`, `dateline`, `lastvisit`, `lastactivity`, `enabled`, `loginapi_moduleid`, `loginapi_userid`, `languageid`, `timezoneoffset`, `enabledst`, `useremailcount`, `allowemail`, `ismanager`) VALUES ('". intval($usergroupid) ."', '". $dbCore->escape(iif(empty($fullname), $email, $fullname)) ."', '". iif($ismd5==true, $password, md5($password)) ."', '". $dbCore->escape($txtpassword) ."', '". DATENOW ."', '0', '0', '". iif($enabled==true, "1", "0") ."', '". intval($loginapi_moduleid) ."', '". $dbCore->escape($loginapi_userid) ."', '". intval($languageid) ."', '". $dbCore->escape($timezone) ."', '". iif($enabledst==true, "1", "0") ."', '1', '". intval($allowemail) ."', '". iif($ismanager==true, "1", "0") ."');");
		$userid = $dbCore->lastInsertId();
		if (!$userid)
		{
			return false;
		}

		$result = insertUserEmail($userid, $email);
		if (!$result)
		{
			return false;
		}

		if (!$disableoutgoingemail)
		{
			if ($enabled == false && $_SWIFT["settings"]["u_enablesveri"] != 1)
			{
				sendRegistrationUpdateMail(MAIL_VERIFICATION, $userid, $fullname, $email, $password);
			} else if ($enabled == true) {
				sendRegistrationUpdateMail(MAIL_SUCCESSREG, $userid, $fullname, $email, $password);
			}
		}

		return $userid;
	} else {
		return false;
	}
}

/**
* Send Verification/Success Mail
*/
function sendRegistrationUpdateMail($mailtype, $userid, $fullname, $email, $password, $tgroupid = false)
{
	global $template, $dbCore, $_SWIFT;
	$template->loadLanguageSection("misc", TEMPLATE_DB);
	require_once ("./includes/functions_mail.php");
	$mailObj = new SWIFT_Mail();

	if ($tgroupid)
	{
		$template->setGroup($tgroupid);
	} else {
		// Set template group
		$template->setGroup(iif(empty($_SWIFT["tgroup"]["tgroupid"]), 1, $_SWIFT["tgroup"]["tgroupid"]));
	}

	// Now try to insert the verification hash and send the email if this user is disabled..
	if ($mailtype == MAIL_VERIFICATION)
	{
		$verifyhash = buildHash();
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."userverifyhash` (`userverifyhashid`, `userid`, `dateline`) VALUES ('". $dbCore->escape($verifyhash) ."', '". intval($userid) ."', '". DATENOW ."');");

		$emailtext = sprintf($_SWIFT["language"]["registervalidatemail"], $fullname, $_SWIFT["swiftpath"], $verifyhash, $_SWIFT["settings"]["general_companyname"]);
		$emailtemplate = "registervalidatemail";
		$emailsubject = sprintf($_SWIFT["language"]["validateemailsubject"], $_SWIFT["settings"]["general_companyname"]);
	} else if($mailtype == MAIL_SUCCESSREG){
		$emailtext = sprintf($_SWIFT["language"]["registersuccess"], $fullname, $email, $password, $_SWIFT["swiftpath"], $_SWIFT["settings"]["general_companyname"]);
		$emailtemplate = "registersuccessmail";
		$emailsubject = sprintf($_SWIFT["language"]["regsuccessmailsubject"], $_SWIFT["settings"]["general_companyname"]);
	}

	$template->assign("contentshtml", getProcessedHTML($emailtext));
	$template->assign("contentstext", getProcessedText($emailtext));

	$template->assign("ishtml", false);
	$emailtext = $template->displayTemplate($emailtemplate, TEMPLATE_DB);

	$template->assign("ishtml", true);
	$emailhtml = $template->displayTemplate($emailtemplate, TEMPLATE_DB);

	$mailObj->setSubject($emailsubject);
	$mailObj->setData($emailhtml, $emailtext);

	$mailObj->sendMail(array($email), $_SWIFT["settings"]["general_returnemail"], $_SWIFT["settings"]["general_companyname"], true);
}

/**
* Send Registration Success Email
*/
function sendRegistrationEmail($userid)
{
	global $dbCore, $_SWIFT, $template;

	$template->loadLanguageSection("misc", TEMPLATE_DB);

	$_user = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."users` AS users LEFT JOIN `". TABLE_PREFIX ."useremails` AS useremails ON (users.userid = useremails.userid) WHERE users.userid = '". intval($userid) ."';");
	if (empty($_user["userid"]))
	{
		return false;
	}

	require_once ("./includes/functions_mail.php");
	$mailObj = new SWIFT_Mail();
	// Set template group
	$template->setGroup(iif(empty($_SWIFT["tgroup"]["tgroupid"]), 1, $_SWIFT["tgroup"]["tgroupid"]));

	// Now try to insert the verification hash and send the email if this user is disabled..
	$emailtext = sprintf($_SWIFT["language"]["registersuccess"], $_user["fullname"], $_user["email"], $_user["userpasswordtxt"], $_SWIFT["swiftpath"], $_SWIFT["settings"]["general_companyname"]);
	$emailtemplate = "registersuccessmail";
	$emailsubject = sprintf($_SWIFT["language"]["regsuccessmailsubject"], $_SWIFT["settings"]["general_companyname"]);

	$template->assign("contentshtml", getProcessedHTML($emailtext));
	$template->assign("contentstext", getProcessedText($emailtext));

	$template->assign("ishtml", false);
	$emailtext = $template->displayTemplate($emailtemplate, TEMPLATE_DB);

	$template->assign("ishtml", true);
	$emailhtml = $template->displayTemplate($emailtemplate, TEMPLATE_DB);

	$mailObj->setSubject($emailsubject);
	$mailObj->setData($emailhtml, $emailtext);

	$mailObj->sendMail(array($_user["email"]), $_SWIFT["settings"]["general_returnemail"], $_SWIFT["settings"]["general_companyname"], true);

	return $_user;
}

/**
* Fetch the given user data
*/
function fetchUser($userid)
{
	global $dbCore, $_SWIFT;

	if (isset($_SWIFT["usercache"][$userid]))
	{
		return $_SWIFT["usercache"][$userid];
	}

	$_user = $_useremaillist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."users` AS users LEFT JOIN `". TABLE_PREFIX ."useremails` AS useremails ON (users.userid = useremails.userid) WHERE users.userid = '". intval($userid) ."';");
	while ($dbCore->nextRecord())
	{
		$_user = $dbCore->Record;
		unset($_user["email"]);
		if (!in_array($dbCore->Record["email"], $_useremaillist))
		{
			$_useremaillist[] = $dbCore->Record["email"];
		}
	}

	$_SWIFT["usercache"][$userid] = $_user;
	$_SWIFT["usercache"][$userid]["emails"] = $_useremaillist;

	return $_SWIFT["usercache"][$userid];
}

/**
* Returns the User ID based on given email address
*/
function getUserEmail($email)
{
	global $dbCore, $_SWIFT;

	if (!empty($_SWIFT["useremailcache"][$email]))
	{
		return $_SWIFT["useremailcache"][$email];
	}

	$_useremail = $dbCore->queryFetch("SELECT `userid`, `email` FROM `". TABLE_PREFIX ."useremails` WHERE `email` = '". $dbCore->escape($email) ."';");
	if (!empty($_useremail["userid"]))
	{
		$_SWIFT["useremailcache"][$_useremail["email"]] = $_useremail["userid"];

		return $_useremail["userid"];
	}

	return false;
}

/**
* Change the users password
*/
function changeUserPassword($userid, $newpassword)
{
	global $dbCore;

	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."users` SET `userpassword` = '". md5($newpassword) ."', `userpasswordtxt` = '". $dbCore->escape($newpassword) ."' WHERE `userid` = '". intval($userid) ."';");

	return true;
}

/**
* Returns template group id from given department id
*/
function getTemplateGroupFromUserGroup($usergroupid)
{
	global $_SWIFT, $dbCore, $datastore;

	$datastore->load("tgroupcache");
	if (!_is_array($_SWIFT["tgroupcache"]))
	{
		return false;
	}

	// We iterate through template group cache and look whether or not this user group is assigned to it
	foreach ($_SWIFT["tgroupcache"] as $key=>$val)
	{
		if ($val["guestusergroupid"] == $usergroupid || $val["regusergroupid"] == $usergroupid)
		{
			// Eureka! Eureka! we found a template group for this
			return $val["tgroupid"];
		}
	}
}

/**
* Update existing User Group
*/
function updateUserGroup($usergroupid, $title, $grouptype, $permarray)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."usergroups` SET `title` = '". $dbCore->escape($title) ."', `grouptype` = '". $dbCore->escape($grouptype) ."' WHERE `usergroupid` = '". intval($usergroupid) ."';");

	// Now update permissions
	if (!count($permarray))
	{
		return false;
	}
	$permsql = array();
	foreach ($permarray as $permkey=>$permval)
	{
		$permsql[] = "('". intval($usergroupid) ."', '". $dbCore->escape($permkey) ."', '". $dbCore->escape($permval) ."')";
	}
	
	if (count($permsql))
	{
		$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."usergroupsettings` (`usergroupid`, `name`, `value`) VALUES ". implode(",", $permsql) .";");
	}

	rebuildUserGroupSettingsCache();

	return true;
}

/**
* Insert a new User Group
*/
function insertUserGroup($title, $grouptype, $permarray)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."usergroups` (`title`, `grouptype`, `ismaster`) VALUES ('". $dbCore->escape($title) ."', '". $dbCore->escape($grouptype) ."', '0');");
	$usergroupid = $dbCore->lastInsertId();
	if (!$usergroupid)
	{
		return false;
	}

	// Now insert permissions
	$permsql = array();
	foreach ($permarray as $permkey=>$permval)
	{
		$permsql[] = "('". intval($usergroupid) ."', '". $dbCore->escape($permkey) ."', '". $dbCore->escape($permval) ."')";
	}
	
	if (count($permsql))
	{
		$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."usergroupsettings` (`usergroupid`, `name`, `value`) VALUES ". implode(",", $permsql) .";");
	}

	rebuildUserGroupSettingsCache();

	return $usergroupid;
}

/**
* Sends a mass mail to all users under the specified groups
*/
function sendUserMassMail($usergroupidlist, $subject, $contents, $fromname, $fromemail)
{
	global $dbCore, $_SWIFT, $template;

	if (!_is_array($usergroupidlist))
	{
		return false;
	}

	require_once ("./includes/functions_mail.php");
	$mailObj = new SWIFT_Mail();

	// Set to master group
	$template->setGroup(1);

	$template->assign("contentshtml", getProcessedHTML($contents));
	$template->assign("contentstext", getProcessedText($contents));

	$template->assign("ishtml", false);
	$emailtext = $template->displayTemplate("usermassmail", TEMPLATE_DB);
	$template->assign("ishtml", true);
	$emailhtml = $template->displayTemplate("usermassmail", TEMPLATE_DB);
		
	$mailObj->setSubject($subject);
	$mailObj->setData($emailhtml, $emailtext);

	$mailcount = 0;
	$dbCore->query("SELECT useremails.email, users.allowemail FROM `". TABLE_PREFIX ."users` AS users LEFT JOIN `". TABLE_PREFIX ."useremails` AS useremails ON (users.userid = useremails.userid) WHERE users.usergroupid IN (". buildIN($usergroupidlist) .");");
	$emaillist = array();
	while ($dbCore->nextRecord())
	{
		if ($dbCore->Record["allowemail"] == 1)
		{
			$emaillist[] = $dbCore->Record["email"];
			$mailcount++;
		}
	}

	if (!count($emaillist))
	{
		return false;
	}

	$mailObj->sendMail($emaillist, $fromemail, $fromname, true);

	return $mailcount;
}

/**
* Renders the EDIT/INSERT User Form
*/
function renderUserForm($type)
{
	global $dbCore, $_SWIFT, $permissions, $module;

	$_ticketcount = 0;
	$_chatcount = 0;
	$_emaillist = $_POST["emaillist"];

	$loadingdata = '<table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder"><tr><td class="row1"><span class="smalltext"><img src="'. $_SWIFT["themepath"] .'loadingcircle.gif" border="0" align="absmiddle" />&nbsp;'. $_SWIFT["language"]["loading"] .'</span></td></tr></table><BR /> ';

	if (($type == EDIT) && $module->isRegistered(MODULE_TICKETS) && count($_emaillist))
	{
		$_total = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."tickets` WHERE `email` IN (". buildIN($_emaillist) .");");
		$_ticketcount = intval($_total["totalitems"]);
	}
	if (($type == EDIT) && $module->isRegistered(MODULE_LIVESUPPORT) && count($_emaillist))
	{
		$_total = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."chatobjects` WHERE `useremail` IN (". buildIN($_emaillist) .");");
		$_chatcount = intval($_total["totalitems"]);
	}

	printFormStart("userform");

	if ($type == EDIT)
	{
		echo '<table cellspacing="0" cellpadding="0" border="0" width="100%" id="caltableopt"><tr style="height: 1em"><td align="left"><div id="calopt"><ul id="tab">
		
		<li><a class="currenttab" href="#" onClick="this.blur(); switchGridTab(\'suedit\', \'userform\');" id="suedit" title="'. $_SWIFT["language"]["tabedit"] .'">'. $_SWIFT["language"]["tabedit"] .'</a></li>';

		foreach ($_emaillist as $key=>$val)
		{
			$_getquery .= "&email[]=".urlencode($val);
		}

		if (($type == DISPLAY || $type == EDIT) && $module->isRegistered(MODULE_TICKETS))
		{
			echo '<li><a href="#" onClick="this.blur(); switchGridTab(\'sutickets\', \'userform\');fetchData(\'sutickets\', \''. $_getquery .'\');" id="sutickets" title="'. sprintf($_SWIFT["language"]["twtickets"], $_ticketcount) .'">'. sprintf($_SWIFT["language"]["tabtickets"], $_ticketcount) .'</a></li>';
		}

		if (($type == DISPLAY || $type == EDIT) && $module->isRegistered(MODULE_LIVESUPPORT))
		{
			echo '<li><a href="#" onClick="this.blur(); switchGridTab(\'suchats\', \'userform\');fetchData(\'suchats\', \''. $_getquery .'\');" id="suchats" title="'. sprintf($_SWIFT["language"]["twchats"], $_chatcount) .'">'. sprintf($_SWIFT["language"]["tabchats"], $_chatcount) .'</a></li>';
		}

		if (($type == DISPLAY || $type == EDIT) && $module->isRegistered(MODULE_TICKETS))
		{
			echo '<li><a href="#" onClick="this.blur(); switchGridTab(\'suticketreports\', \'userform\');fetchData(\'suticketreports\', \''. intval($_POST["userid"]) .'\');" id="suticketreports" title="'. $_SWIFT["language"]["tabticketreports"] .'">'. $_SWIFT["language"]["tabticketreports"] .'</a></li>';
		}
		echo '</ul></div></td></tr>'.SWIFT_CRLF;

		echo '<tr style="height: 1em"><td align="left">'.SWIFT_CRLF;

		// ======= EDIT TAB =======
		echo '<div id="tab_suedit" style="DISPLAY: block;" class="tabcontent">';
		echo '<table border="0" cellpadding="3" cellspacing="1" width="100%" class="tborder">';
	} else {
		printMainTableHeader($_SWIFT["language"]["userdetails"]);
	}

	if ($type == INSERT)
	{
		printDescRow($_SWIFT["language"]["generalfields"]);
	}

	printTextRow("fullname", $_SWIFT["language"]["usrfullname"], $_SWIFT["language"]["desc_usrfullname"], "text", $_POST["fullname"]);

	if ($type == INSERT)
	{
		printTextRow("email", $_SWIFT["language"]["usremail"], $_SWIFT["language"]["desc_usremail"], "text", $_POST["email"]);		
	}

	printTextRow("password", iif($type==INSERT, $_SWIFT["language"]["usrpassword"], $_SWIFT["language"]["usrpasswordreset"]), $_SWIFT["language"]["desc_usrpassword"], "password", $_POST["password"]);

	printTextRow("passwordconfirm", $_SWIFT["language"]["usrpasswordconfirm"], $_SWIFT["language"]["desc_usrpasswordconfirm"], "password", $_POST["passwordconfirm"]);

	printUserGroupSelectRow("usergroupid", $_SWIFT["language"]["usrformgroup"], $_SWIFT["language"]["desc_usrformgroup"], true);

	$options = array();
	$options[0]["title"] = $_SWIFT["language"]["uuser"];
	$options[0]["value"] = "0";
	$options[0]["selected"] = true;
	$options[1]["title"] = $_SWIFT["language"]["umanager"];
	$options[1]["value"] = "1";
	printSelectRow("ismanager", $_SWIFT["language"]["usertype"], $_SWIFT["language"]["desc_usertype"], $options);

	if ($module->isRegistered(MODULE_TICKETS))
	{
		$options = array();
		$index = 1;
		$options[0]["title"] = $_SWIFT["language"]["noslaplan"];
		$options[0]["value"] = "0";
		$options[0]["selected"] = true;
		$dbCore->query("SELECT `slaplanid`, `title` FROM `". TABLE_PREFIX ."slaplans` ORDER BY `title` ASC;");
		while ($dbCore->nextRecord())
		{
			$options[$index]["title"] = $dbCore->Record["title"];
			$options[$index]["value"] = $dbCore->Record["slaplanid"];
			$index++;
		}
		printSelectRow("slaplanid", $_SWIFT["language"]["uslaplan"], $_SWIFT["language"]["desc_uslaplan"], $options);
	}

	renderStaffCustomFields(CUSTOMFIELD_USER, false, iif($type==EDIT, $_POST["userid"], 0));
	
	printSubmitRow(iif($type==INSERT,$_SWIFT["language"]["insertuser"],$_SWIFT["language"]["updateuser"]));

	if ($type == EDIT)
	{
		echo '</table><BR />';
		echo '</div>';

		// ======= TICKETS =======
		echo '<div id="tab_sutickets" style="DISPLAY: none;" class="tabcontent">'. $loadingdata .'</div>';

		// ======= CHAT HISTORY =======
		echo '<div id="tab_suchats" style="DISPLAY: none;" class="tabcontent">'. $loadingdata .'</div>';

		// ======= TICKET REPORTS =======
		echo '<div id="tab_suticketreports" style="DISPLAY: none;" class="tabcontent">'. $loadingdata .'</div>';

		// ======= CHAT REPORTS =======
		echo '<div id="tab_suchatreports" style="DISPLAY: none;" class="tabcontent">'. $loadingdata .'</div>';
		echo '</td></tr></table>';

	} else {
		printMainTableFooter();
	}

	addHiddenField("_m", "core");
	addHiddenField("_a", iif($type==INSERT, "insertuser", "edituser"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("userid", $_POST["userid"]);
	}
	printFormEnd();
}

/**
* Renders the EDIT/INSERT User Group Form
*/
function renderUserGroupForm($type)
{
	global $dbCore, $_SWIFT, $permissions, $module;

	printFormStart("usergroupform");
	printMainTableHeader($_SWIFT["language"]["usergroupdetails"]);

	printDescRow($_SWIFT["language"]["generalfields"]);

	printTextRow("title", $_SWIFT["language"]["grouptitle"], $_SWIFT["language"]["desc_grouptitle"], "text", $_POST["title"]);

	$options[0]["title"] = $_SWIFT["language"]["ugroupguest"];
	$options[0]["value"] = USERGROUP_GUEST;
	$options[0]["selected"] = 1;
	$options[1]["title"] = $_SWIFT["language"]["ugroupregistered"];
	$options[1]["value"] = USERGROUP_REGISTERED;

	printSelectRow("grouptype", $_SWIFT["language"]["ugrouptype"], $_SWIFT["language"]["desc_ugrouptype"], $options);

	if ($module->isRegistered(MODULE_TICKETS))
	{
		$options = array();
		$index = 1;
		$options[0]["title"] = $_SWIFT["language"]["noslaplan"];
		$options[0]["value"] = "0";
		$options[0]["selected"] = true;
		$dbCore->query("SELECT `slaplanid`, `title` FROM `". TABLE_PREFIX ."slaplans` ORDER BY `title` ASC;");
		while ($dbCore->nextRecord())
		{
			$options[$index]["title"] = $dbCore->Record["title"];
			$options[$index]["value"] = $dbCore->Record["slaplanid"];
			$index++;
		}
		printSelectRow("slaplanid", $_SWIFT["language"]["ugslaplan"], $_SWIFT["language"]["desc_ugslaplan"], $options);
	}


	renderStaffCustomFields(CUSTOMFIELD_USERGROUP, false, iif($type==EDIT, $_POST["usergroupid"], 0));

	require_once ("./modules/core/config_userpermissions.php");
	foreach ($_userperm as $key=>$val)
	{
		if ($module->isRegistered($key))
		{
			printDescRow($_SWIFT["language"]["perm_".$key]);

			foreach ($val as $permkey=>$perm)
			{
				if ($permissions[$perm] == "1")
				{
					$permres = true;
				} else if ($permissions[$perm] == "") {
					$permres = true;
				} else {
					$permres = false;
				}

				printYesNoRow("perm[". $perm ."]", $_SWIFT["language"][$perm], "", $permres);
			}
		}
	}
	
	printSubmitRow(iif($type==INSERT,$_SWIFT["language"]["insertgroup"],$_SWIFT["language"]["updategroup"]));

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", iif($type==INSERT, "insertusergroup", "editusergroup"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("usergroupid", $_POST["usergroupid"]);
	}
	printFormEnd();
}

/**
* Rebuild user group permissions.. Used during setup and upgrade
*/
function rebuildUserGroupPermissions()
{
	global $dbCore;

	// Get all registered modules
	$modulelist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."settings` WHERE `section` = 'registeredmodules';");
	while ($dbCore->nextRecord())
	{
		$modulelist[] = $dbCore->Record["vkey"];
	}
	$modulelist[] = MODULE_CORE;

	// Get all User Group IDs
	$usergroupidlist = array();
	$dbCore->query("SELECT `usergroupid` FROM `". TABLE_PREFIX ."usergroups` ORDER BY `usergroupid` ASC;");
	while ($dbCore->nextRecord())
	{
		$usergroupidlist[] = $dbCore->Record["usergroupid"];
	}

	$_settingcache = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."usergroupsettings`;");
	while ($dbCore->nextRecord())
	{
		$_settingcache[$dbCore->Record["usergroupid"]][$dbCore->Record["name"]] = intval($dbCore->Record["value"]);
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."usergroupsettings`;");

	// Rebuild all User permissions
	require_once ("./modules/core/config_userpermissions.php");
	$permsql = array();
	foreach ($_userperm as $key=>$val)
	{
		if (in_array($key, $modulelist))
		{
			foreach ($val as $permkey=>$permval)
			{
				for ($ii=0; $ii<count($usergroupidlist); $ii++)
				{
					if (isset($_settingcache[$usergroupidlist[$ii]][$permval]))
					{
						$_setvalue = $_settingcache[$usergroupidlist[$ii]][$permval];
					} else {
						$_setvalue = 1;
					}
					$permsql[] = "('". intval($usergroupidlist[$ii]) ."', '". $permval ."', '". $_setvalue ."')";
				}
			}
		}
	}

	$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."usergroupsettings` (`usergroupid`, `name`, `value`) VALUES ". implode(",", $permsql) .";");
}

/**
* Rebuilds the User Group Permission Cache
*/
function rebuildUserGroupSettingsCache()
{
	global $_SWIFT, $dbCore, $datastore;

	$groupsettings = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."usergroupsettings` ORDER BY `ugroupsettingid` ASC;");
	while ($dbCore->nextRecord())
	{
		$groupsettings[$dbCore->Record["usergroupid"]][$dbCore->Record["name"]] = $dbCore->Record["value"];
	}

	$datastore->update("usergroupsettingcache", $groupsettings);
}

/**
* Send the Lost Password Email for the user
*/
function sendLostPasswordEmail($userid)
{
	global $dbCore, $_SWIFT, $template;

	// Load the user
	$_user = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."users` WHERE `userid` = '". intval($userid) ."';");
	if (empty($_user["userid"]))
	{
		return false;
	}

	// Loaded, Load the Primary Email
	$_useremail = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."useremails` WHERE `userid` = '". intval($userid) ."' ORDER BY `useremailid` ASC LIMIT 1;");
	if (empty($_useremail["email"]))
	{
		return false;
	}

	$template->setGroup($_SWIFT["tgroup"]["tgroupid"]);
	$template->assign("userfullname", $_user["fullname"]);
	$template->assign("userpassword", $_user["userpasswordtxt"]);
	$template->assign("primaryemail", $_useremail["email"]);

	$template->assign("ishtml", true);
	$_templateresulthtml = $template->displayTemplate("email_lostpass", TEMPLATE_DB);
	$template->assign("ishtml", false);
	$_templateresulttext = $template->displayTemplate("email_lostpass", TEMPLATE_DB);

	require_once ("./includes/functions_mail.php");
	$mailObj = new SWIFT_Mail();

	$mailObj->setSubject(sprintf($_SWIFT["language"]["lpmailsubject"], $_SWIFT["settings"]["general_companyname"]));
	$mailObj->setData($_templateresulthtml, $_templateresulttext);
	$mailObj->sendMail($_useremail["email"], $_SWIFT["settings"]["general_returnemail"], $_SWIFT["settings"]["general_companyname"], false);

	return true
		;
}
?>